/*

*/


// HACK: 
// must create a SimpleDateFormat to parse a Date class toString()'s output.
// Needed because the code in a date object toString() can append timezone strings 
// (i.e. BST) that its parse() method cannot decode !
static SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");

// represents records read from data file 

class DataFileRecord {

  String user;
  String band;
  String album;
  String track;
  Date dateTime;

  DataFileRecord(String user, String band, String album, String track, Date dateTime) {
    this.user = user;
    this.band = band;
    this.album = album;
    this.track = track;
    this.dateTime = dateTime; 
  }
  
  String toString() {
     return String.format("%s,%s,%s,%s,%s",user,band,album,track,dateTime); 
  }

}

// loadStrings is NOT suitable for processing very large files
// so we wrote a csv file reader that reads one record at a time

class DataFileReader {
  
  BufferedReader reader;
  int numRead;
  
  DataFileReader(String fname) {
    this.reader = createReader(fname);
  }
  
  DataFileRecord parseRecord(String data) {
    
    DataFileRecord record = null; 
    String[] fields = data.split(",",5); 
    
    try {  
      record = new DataFileRecord(fields[0],fields[1],fields[2],fields[3],sdf.parse(fields[4]));
      Date d = sdf.parse(fields[4]);  
    } catch (Exception e) {
      println("parse error on line " + numRead);
      e.printStackTrace();
    } 
 
    return record;
  }
 
  
  DataFileRecord readRecord() {
    
    if (reader == null) return null;
    
    DataFileRecord record = null;
    
    try {;
      String data;
      // repeat until eof or valid record
      do {
        if ( (data = reader.readLine()) != null) {
          record = parseRecord(data);  
        }
      } while(data != null && record == null);
    } 
    catch (IOException e) {
      println("parse error on line " + numRead);
      e.printStackTrace();
    } 
    
    return record;
  }
  
  void close() {
    if (reader != null) {
      // try and close the file
      try {
        reader.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      reader = null;
    }
  } 
}

